/*
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
package io.trino.spooling.filesystem.encryption;

import java.util.List;
import java.util.Map;

import static com.google.common.base.Preconditions.checkArgument;
import static com.google.common.collect.ImmutableMap.toImmutableMap;
import static java.util.Locale.ENGLISH;

public class HeadersUtils
{
    private HeadersUtils() {}

    public static String getOnlyHeader(Map<String, List<String>> headers, String name)
    {
        String headerName = normalizeHeaderNameCase(name);
        List<String> values = headers.get(headerName);
        checkArgument(values != null && !values.isEmpty(), "Required header %s was not found", headerName);
        checkArgument(values.size() == 1, "Required header %s contains more than one value", headerName);
        return values.getFirst();
    }

    static Map<String, List<String>> normalizeHeaders(Map<String, List<String>> headers)
    {
        return headers.entrySet()
                .stream()
                .collect(toImmutableMap(
                        entry -> normalizeHeaderNameCase(entry.getKey()),
                        entry -> List.copyOf(entry.getValue())));
    }

    static String normalizeHeaderNameCase(String headerName)
    {
        return headerName.toLowerCase(ENGLISH);
    }
}
